//! 地址生成器模块

use rand::seq::SliceRandom;
use rand::Rng;
use once_cell::sync::Lazy;
use std::fs;

/// 中国省份
const PROVINCES: &[&str] = &[
    "北京市", "天津市", "河北省", "山西省", "内蒙古自治区",
    "辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省",
    "浙江省", "安徽省", "福建省", "江西省", "山东省",
    "河南省", "湖北省", "湖南省", "广东省", "广西壮族自治区",
    "海南省", "重庆市", "四川省", "贵州省", "云南省",
    "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏回族自治区",
    "新疆维吾尔自治区"
];

/// 城市后缀
const CITY_SUFFIXES: &[&str] = &["市", "县", "区"];

/// 街道后缀
const STREET_SUFFIXES: &[&str] = &["街", "路", "大道", "巷", "胡同", "里"];

/// 从文件加载街道前缀
static STREET_PREFIXES: Lazy<Vec<String>> = Lazy::new(|| {
    load_data_from_file("data/generators/address/street_prefixes.txt")
});

/// 从文件加载美国州名
static US_STATES: Lazy<Vec<String>> = Lazy::new(|| {
    load_data_from_file("data/generators/address/us_states.txt")
});

/// 从文件加载美国城市
static US_CITIES: Lazy<Vec<String>> = Lazy::new(|| {
    load_data_from_file("data/generators/address/us_cities.txt")
});

/// 从文件加载数据的辅助函数
fn load_data_from_file(file_path: &str) -> Vec<String> {
    match fs::read_to_string(file_path) {
        Ok(content) => content
            .lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect(),
        Err(_) => {
            // 如果文件不存在，返回默认数据
            match file_path {
                "data/generators/address/street_prefixes.txt" => vec![
                    "长安".to_string(), "中山".to_string(), "人民".to_string(), 
                    "解放".to_string(), "建设".to_string(), "和平".to_string()
                ],
                "data/generators/address/us_states.txt" => vec![
                    "California".to_string(), "Texas".to_string(), "Florida".to_string(),
                    "New York".to_string(), "Illinois".to_string(), "Pennsylvania".to_string()
                ],
                "data/generators/address/us_cities.txt" => vec![
                    "New York".to_string(), "Los Angeles".to_string(), "Chicago".to_string(),
                    "Houston".to_string(), "Phoenix".to_string(), "Philadelphia".to_string()
                ],
                _ => vec!["Default".to_string()]
            }
        }
    }
}

/// 生成中国省份
pub fn zh_province() -> String {
    let mut rng = rand::thread_rng();
    PROVINCES.choose(&mut rng).unwrap().to_string()
}

/// 生成中国城市
pub fn zh_city() -> String {
    let mut rng = rand::thread_rng();
    let prefix_len = rng.gen_range(2..=4);
    let mut city = String::new();
    
    // 生成城市名前缀
    for _ in 0..prefix_len {
        city.push(crate::regions::china::rand_hanzi());
    }
    
    // 添加后缀
    city.push_str(CITY_SUFFIXES.choose(&mut rng).unwrap());
    city
}

/// 生成中国街道
pub fn zh_street() -> String {
    let mut rng = rand::thread_rng();
    let prefix = STREET_PREFIXES.choose(&mut rng).unwrap();
    let suffix = STREET_SUFFIXES.choose(&mut rng).unwrap();
    format!("{}{}", prefix, suffix)
}

/// 生成中国完整地址
pub fn zh_address() -> String {
    let mut rng = rand::thread_rng();
    let province = zh_province();
    let city = zh_city();
    let street = zh_street();
    let number = rng.gen_range(1..=999);
    
    format!("{}{}{}{number}号", province, city, street, number = number)
}

/// 生成邮政编码
pub fn postal_code() -> String {
    let mut rng = rand::thread_rng();
    // 中国邮政编码首位数字为1-8
    let first_digit = rng.gen_range(1..=8);
    let remaining = rng.gen_range(10000..=99999);
    format!("{}{:05}", first_digit, remaining)
}

/// 生成美国州名
pub fn us_state() -> String {
    let mut rng = rand::thread_rng();
    US_STATES.choose(&mut rng).unwrap().clone()
}

/// 生成美国城市
pub fn us_city() -> String {
    let mut rng = rand::thread_rng();
    US_CITIES.choose(&mut rng).unwrap().clone()
}

/// 生成美国邮编
pub fn us_postal_code() -> String {
    let mut rng = rand::thread_rng();
    format!("{:05}", rng.gen_range(10000..=99999))
}

/// 生成中国邮编（别名）
pub fn zh_postal_code() -> String {
    postal_code()
}

/// 生成坐标
pub fn coordinate() -> (f64, f64) {
    coordinates()
}

/// 生成中国坐标
pub fn china_coordinate() -> (f64, f64) {
    let mut rng = rand::thread_rng();
    let lat = rng.gen_range(18.0..=54.0); // 中国纬度范围
    let lng = rng.gen_range(73.0..=135.0); // 中国经度范围
    (lat, lng)
}

/// 生成美国地址
pub fn us_address() -> String {
    let mut rng = rand::thread_rng();
    let number = rng.gen_range(1..=9999);
    let street_names = ["Main St", "Oak Ave", "Pine Rd", "Elm Dr", "Maple Ln"];
    let street = street_names.choose(&mut rng).unwrap();
    let city = us_city();
    let state = us_state();
    let zip = rng.gen_range(10000..=99999);
    
    format!("{} {}, {}, {} {}", number, street, city, state, zip)
}

/// 生成经度
pub fn longitude() -> f64 {
    let mut rng = rand::thread_rng();
    rng.gen_range(-180.0..=180.0)
}

/// 生成纬度
pub fn latitude() -> f64 {
    let mut rng = rand::thread_rng();
    rng.gen_range(-90.0..=90.0)
}

/// 生成坐标点
pub fn coordinates() -> (f64, f64) {
    (latitude(), longitude())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zh_province() {
        let province = zh_province();
        assert!(!province.is_empty());
        assert!(PROVINCES.contains(&province.as_str()));
    }

    #[test]
    fn test_zh_address() {
        let address = zh_address();
        assert!(!address.is_empty());
        assert!(address.contains("号"));
    }

    #[test]
    fn test_postal_code() {
        let code = postal_code();
        assert_eq!(code.len(), 6);
        assert!(code.chars().all(|c| c.is_ascii_digit()));
    }

    #[test]
    fn test_coordinates() {
        let (lat, lng) = coordinates();

        // 经度有效范围是[-180, 180]，纬度是[-90, 90]
        assert!(lng >= -180.0 && lng <= 180.0);
        assert!(lat >= -90.0 && lat <= 90.0, "lat is: {}", lat);
    }
}